package com.zbiti.anvil.basic.admin.gateway.common.aspect;

import com.zbiti.anvil.security.delegate.IUserAuthenticationHandler;
import com.zbiti.framework.security.api.bean.IUser;
import com.zbiti.module.system.base.api.domain.SysUserDomain;
import com.zbiti.module.system.base.api.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户登录权限校验处理
 *
 * @author Fanyc
 * @date 2021-03-04 14:46
 */
@Component
public class UserAuthenticationHandler implements IUserAuthenticationHandler {

    /**
     * 获取用户服务
     */
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 登录成功信息
     *
     * @param loginName 用户登录名
     * @param ip        登录IP
     */
    @Override
    public void doLoginSuccess(String loginName, String ip) {
        IUser iUser = sysUserService.selectUserByLoginName(loginName);
        if (iUser instanceof SysUserDomain) {
            SysUserDomain sysUserDomain = (SysUserDomain) iUser;
            // 如果是锁定状态或存在重试次数则自动清除
            if (SysUserDomain.UserStatusEnum.LOCKED.code.equals(sysUserDomain.getStatus())
                    || (sysUserDomain.getRetryPwdCount() != null && sysUserDomain.getRetryPwdCount() > 0)) {
                this.sysUserService.unlockUser(loginName);
            }
        }
    }

    /**
     * 退出成功信息
     *
     * @param loginName 用户登录名
     */
    @Override
    public void doLogOutSuccess(String loginName) {
        // do nothing
    }

    /**
     * 登录失败信息
     *
     * @param loginName 用户登录名
     * @param message   错误信息
     */
    @Override
    public void doLoginFailure(String loginName, String message) {
        // 更新数据库用户状态
        sysUserService.updateLoginFailure(loginName);
    }

}
